﻿@page "/locations"
@using Microsoft.EntityFrameworkCore
@using Wms.Core.Entities
@inject Wms.Data.WarehouseDbContext DbContext
@inject IJSRuntime JSRuntime

<div class="container-fluid py-4">
    <!-- 页面标题 -->
    <h4 class="text-primary mb-4">
        <span class="oi oi-map-marker me-2"></span> 库位管理
    </h4>

    <!-- 添加库位表单 -->
    <div class="card shadow-sm mb-4">
        <div class="card-body">
            <form @onsubmit="HandleAddLocation">
                <div class="row g-3 align-items-center">
                    <div class="col-md-3">
                        <select class="form-select form-select-lg"
                        @bind="selectedWarehouseId"
                        required>
                            <option value="">请选择所属仓库</option>
                            @foreach (var w in warehouses)
                            {
                                <option value="@w.Id">@w.Name</option>
                            }
                        </select>
                    </div>
                    <div class="col-md-3">
                        <input class="form-control form-select-lg"
                        @bind="newLocationCode"
                        placeholder="请输入库位编码（如：A01-02）"
                        maxlength="20"
                        required />
                    </div>
                    <div class="col-md-3">
                        <input class="form-control form-select-lg"
                        @bind="newLocationName"
                        placeholder="请输入库位名称（如：A01-02）"
                        maxlength="20"
                        required />
                    </div>
                    <div class="col-md-3">
                        <button type="submit"
                        class="btn btn-success btn-lg w-100"
                        disabled="@(selectedWarehouseId == null || string.IsNullOrWhiteSpace(newLocationCode))">
                            <span class="oi oi-plus me-1"></span> 添加库位
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- 库位列表 -->
    <div class="card shadow-sm">
        <div class="card-header bg-white d-flex justify-content-between align-items-center">
            <h6 class="mb-0">库位列表</h6>
            <span class="badge bg-info text-dark rounded-pill">@locations.Count</span>
        </div>
        <div class="card-body p-0">
            @if (!locations.Any())
            {
                <div class="text-center py-5">
                    <img src="https://cdn.jsdelivr.net/gh/twbs/icons/icons/geo-alt.svg" alt="空库位" width="48" class="mb-3 opacity-50" />
                    <p class="text-muted">暂无库位，请先选择仓库并添加。</p>
                </div>
            }
            else
            {
                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0">
                        <thead class="table-light">
                            <tr>
                                <th scope="col">编号</th>
                                <th scope="col">库位编码</th>
                                <th scope="col">库位名称</th>
                                <th scope="col">所属仓库</th>
                                <th scope="col" class="text-center" style="width: 150px;">操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach (var loc in locations)
                            {
                                <tr>
                                    <td><code>@loc.Id</code></td>
                                    <td>
                                        <strong class="text-primary">@loc.Code</strong>
                                    </td>
                                    <td>
                                        <strong>@loc.Name</strong>
                                    </td>
                                    <td>
                                        <span class="badge bg-secondary">@loc.Warehouse?.Name</span>
                                    </td>
                                    <td class="text-center">
                                        <button class="btn btn-sm btn-outline-danger"
                                        @onclick="() => ConfirmDelete(loc.Id, loc.Code)"
                                        title="删除库位">
                                            <span class="oi oi-trash"></span> 删除
                                        </button>
                                    </td>
                                </tr>
                            }
                        </tbody>
                    </table>
                </div>
            }
        </div>
    </div>
</div>

<!-- 删除确认模态框 -->
@if (showDeleteModal)
{
    <div class="modal fade show d-block" tabindex="-1" style="display: block; background: rgba(0,0,0,0.5);">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title text-danger">
                        <span class="oi oi-warning me-2"></span> 确认删除
                    </h5>
                    <button type="button" class="btn-close" @onclick="() => showDeleteModal = false"></button>
                </div>
                <div class="modal-body">
                    <p>确定要删除库位 <strong>"@deletingLocationCode"</strong> 吗？</p>
                    <p class="text-danger small">此操作不可撤销！</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" @onclick="() => showDeleteModal = false">取消</button>
                    <button type="button" class="btn btn-danger" @onclick="ExecuteDelete">确认删除</button>
                </div>
            </div>
        </div>
    </div>
}

@code {
    private int? selectedWarehouseId;
    private string newLocationCode = string.Empty;
    private string newLocationName = string.Empty;
    private List<Location> locations = new();
    private List<Warehouse> warehouses = new();

    // 删除模态框相关
    private bool showDeleteModal = false;
    private int deletingLocationId;
    private string deletingLocationCode = string.Empty;

    protected override void OnInitialized()
    {
        warehouses = DbContext.Warehouses.ToList();
        LoadLocations();
    }

    private void LoadLocations()
    {
        locations = DbContext.Locations
            .Include(l => l.Warehouse)
            .OrderBy(l => l.Warehouse.Name)
            .ThenBy(l => l.Code)
            .ToList();
    }

    private async Task HandleAddLocation()
    {
        if (string.IsNullOrWhiteSpace(newLocationName))
        {
            // 显示错误提示
            await JSRuntime.InvokeVoidAsync("alert", "库位名称不能为空");
            return;
        }
        if (selectedWarehouseId == null || string.IsNullOrWhiteSpace(newLocationCode)){
            await JSRuntime.InvokeVoidAsync("alert", "请选择所属仓库");
            return;
        }

        var code = newLocationCode.Trim();
        var name = newLocationName.Trim();

        // 检查编码是否已存在
        if (locations.Any(l => l.Code.Equals(code, StringComparison.OrdinalIgnoreCase)))
        {
            await JSRuntime.InvokeVoidAsync("alert", "该库位编码已存在！");
            return;
        }

        var location = new Location
            {
                Code = code,
                Name = name,
                WarehouseId = selectedWarehouseId.Value
            };

        DbContext.Locations.Add(location);
        await DbContext.SaveChangesAsync();

        // 重新加载（保持排序）
        LoadLocations();
        newLocationCode = string.Empty;
        newLocationName = string.Empty;

        await JSRuntime.InvokeVoidAsync("alert", $"库位 '{code}' 添加成功！");
    }

    private void ConfirmDelete(int id, string code)
    {
        deletingLocationId = id;
        deletingLocationCode = code;
        showDeleteModal = true;
    }

    private async Task ExecuteDelete()
    {
        var location = DbContext.Locations.Find(deletingLocationId);
        if (location != null)
        {
            DbContext.Locations.Remove(location);
            DbContext.SaveChanges();
            LoadLocations(); // 重新加载

            await JSRuntime.InvokeVoidAsync("alert", $"库位 '{deletingLocationCode}' 已删除。");
        }
        showDeleteModal = false;
    }
}